﻿using System;
using System.Collections.Generic;
using System.Threading;
using System.Text;

namespace MCDS
{
    public class MCDSService
    {
        private static HashSet<MCDSInterface> listeners = new HashSet<MCDSInterface>();
        private static object lockthis = new object();
        private static int updateTime = 1;
        private static string tilesPath = "";
        private static string clave = "";

        public static int UpdateTime
        {
            get
            {
                return updateTime;
            }
            set
            {
                updateTime = value;
            }
        }
        public static string TilesPath
        {
            get
            {
                return tilesPath;
            }
            set
            {
                tilesPath = value;
            }
        }
        public static string Clave
        {
            get
            {
                return clave;
            }
            set
            {
                clave = value;
            }
        }
        public static bool add(MCDSInterface litener)
        {
            bool ret;
            lock (lockthis)
                ret = listeners.Add(litener);

            return ret;
        }

        public static bool remove(MCDSInterface litener)
        {
            bool ret;
            lock (lockthis)
                ret = listeners.Add(litener);

            return ret;
        }

        public static void service()
        {
            try
            {
                // Do service stuff here
                while (true)
                {
                    // Crear el objeto MCDS
                    MCDS sistemaRecomendador = new MCDS(tilesPath);
                    // Notificar a los listeners que hay recomendaciones disponible
                    lock (lockthis)
                    {
                        foreach (MCDSInterface listener in listeners)
                            listener.notify(sistemaRecomendador.Recomendaciones(clave));
                    }

                    // Al finalizar, dormirse un rato
                    // La información meteorológica se actualizará cada 10 minutos
                    Thread.Sleep(new TimeSpan(0, 0, updateTime, 0));
                }
            }
            catch (ThreadAbortException) { }
        }
    }
}
